package com.arelikebrothers.demo.concurrent.jdk;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * Created by lennon on 01/05/2017.
 */
public class CyclicBarrierDemo {
    public static class Soldier implements Runnable {
        private String soldier;
        private CyclicBarrier cyclicBarrier;

        public Soldier(String soldier, CyclicBarrier cyclicBarrier) {
            this.soldier = soldier;
            this.cyclicBarrier = cyclicBarrier;
        }

        @Override
        public void run() {
            try {
                // 等待所有士兵到齐
                cyclicBarrier.await();
                dowork();
                cyclicBarrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }

        private void dowork() throws InterruptedException {
            Thread.sleep(new Random().nextInt(10) * 1000);
            System.out.println("Soldier " + soldier + " 完成任务！");
        }
    }

    public static class BarrierRun implements Runnable {
        boolean flag;
        int N;

        public BarrierRun(boolean flag, int n) {
            this.flag = flag;
            N = n;
        }

        @Override
        public void run() {
            if (flag) {
                System.out.println("司令：[士兵" + N + "个, 完成任务!]");
            } else {
                System.out.println("司令：[士兵" + N + "个, 集合完毕!]");
                flag = true;
            }
        }
    }

    public static void main(String[] args) {
        int N = 10;
        Thread[] allSoldierThread = new Thread[N];
        boolean flag = false;
        CyclicBarrier cyclic = new CyclicBarrier(N, new BarrierRun(flag, N));
        System.out.println("集合队伍");

        for (int i = 0; i < N; i++) {
            System.out.println("士兵" + i + " 报到！");
            allSoldierThread[i] = new Thread(new Soldier("士兵" + i, cyclic));
            allSoldierThread[i].start();
        }
    }
}
